//
//  HomeFlipItemView.m
//  BaoVn
//
//  Created by Phuong Le on 11/24/14.
//  Copyright (c) 2014 Le Anh Tai. All rights reserved.
//

#import "HomeFlipItemView.h"
#import "WebsiteItemView.h"

@implementation HomeFlipItemView

- (instancetype)init
{
    if (self = [super init])
    {
        _margin = 0;
        _padding = 4;
    }
    
    return self;
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    
    NSInteger top = _margin;
    NSInteger hei = (self.height - _margin*2 - (_itemViews.count - 1)*_padding)/_itemViews.count;
    
    // Layout n-1 items
    BaseNewsItemView *itemView = nil;
    
    for (NSInteger i = 0; i < _data.count; i++)
    {
        itemView = [_itemViews objectAtIndex:i];
        itemView.frame = RECT(_margin, top, self.width - _margin*2, hei);
        
        top = itemView.bottom + _padding;
    }
    
//    // Layout last item
//    top = _margin;
//    
//    // lastItem - 1
//    if (itemView)
//    {
//        top = itemView.bottom + _padding;
//    }
//    
//    itemView = [_itemViews objectAtIndex:_data.count-1];
//    itemView.frame = RECT(_margin, top, self.width - _margin*2, self.height - top);
}

- (void)loadDataWithValue:(id)value
{
    _data = value;
    
    [self initializeItemViews:_data.count];
    
    for (NSInteger i = 0; i < _data.count; i++)
    {
        BaseNewsItemView *itemView = [_itemViews objectAtIndex:i];
        [itemView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandler:)]];
        
        NSDictionary *dict = [_data objectAtIndex:i];
        [itemView loadData:dict];
    }
}

- (void)initializeItemViews:(NSInteger)numberOfItems
{
    if (_itemViews == nil)
    {
        _itemViews = [[NSMutableArray alloc] init];
    }
    
    //reuse childViews
    if (_itemViews.count == numberOfItems)
    {
        return;
    }
    
    for (UIView *view in _itemViews)
    {
        [view removeFromSuperview];
    }
    
    [_itemViews removeAllObjects];
    
    for (NSInteger i = 0; i < numberOfItems; i++)
    {
        UIView *itemView = [[WebsiteItemView alloc] init];
        
        [self addSubview:itemView];
        [_itemViews addObject:itemView];
    }
}

- (void)tapGestureHandler:(UITapGestureRecognizer *)gesture
{
    BaseNewsItemView *view = (BaseNewsItemView *)gesture.view;
    
    if ([self.delegate respondsToSelector:@selector(flipViewItem:didSelectItem:withData:)])
    {
        [self.delegate flipViewItem:self didSelectItem:view withData:view.data];
    }
}
@end
